$(document).ready(function() {
    initBehavior();
    //preparar tiempo de caducidad
    var dueDate = new Date();
    dueDate.setSeconds(dueDate.getSeconds() + parseInt(appBosch.maxTime));
    var clockTemplate = ''
                    + '<span>%M</span> min '
                    + '<span>%S</span> seg';
    if( appBosch.maxTime >= 60*60 ){// mayor a una hora
        clockTemplate = ''
                    + '<span>%H</span> hrs '
                    + '<span>%M</span> min '
                    + '<span>%S</span> seg';
    }
    $('#clock').countdown(dueDate)
            .on('update.countdown', function(event) {
                $(this).html(event.strftime(clockTemplate));
                })
            .on('finish.countdown', function(event){
                $(this).html('Tiempo finalizado');
                quitExamBy('time');
            });
    
    appBosch.template = kendo.template($("#tmpQuestion").html());
    appBosch.templateQuit = kendo.template($("#quitWindowTemplate").html());
    appBosch.templateSkip = kendo.template($("#skipWindowTemplate").html());
    appBosch.templateProgress = kendo.template($("#progressTemplate").html());
    getNextQuestion({}); //obtener la primer pregutna s
} );

function initBehavior(){
    $("#nextQuestion").on("click",function(e){
        e.preventDefault();
        if($('input[name=answer]:checked').length){
            var data        = {};
            data.id         = $(".question").data("idQ");
            data.answers    = [];
            var checkboxValues = [];
            $('input[name=answer]:checked').each(function(index, elem) {
                data.answers.push($(elem).val());
            });
            $(this).prop('disabled', true);
            getNextQuestion(data);
        }else{
            var quitWindow = $("#dlg").kendoWindow({
                title: "Imposible avanzar",
                modal:true,
                visible: false, //the window will not appear before its .open method is called
                width: 300,
                height: 100
            }).data("kendoWindow");
            quitWindow.content(appBosch.qMessages.txtSelectAnswer); 
            quitWindow.open().center();  
        }
    });
    $("#quitExam").on("click",function(){
        var quitWindow = $("#window").kendoWindow({
            title: "Abandonar examen",
            modal:true,
            visible: false, //the window will not appear before its .open method is called
            width: 650,
            height: 200
        }).data("kendoWindow");
        quitWindow.content(appBosch.templateQuit(appBosch.qMessages)); //send the row data object to the template and render it
        quitWindow.open().center();  

        $("#yesButton").on('click',function(){
            quitExamBy('user');
            quitWindow.close();
        });
        $("#noButton").on('click',function(){
            quitWindow.close();
        });
    });
    
    $("#skipQuestion").on("click",function(){
        if($('input[name=answer]:checked').length){
            var skipWindow = $("#window").kendoWindow({
                title: "Saltar pregunta",
                modal:true,
                visible: false, //the window will not appear before its .open method is called
                width: 650,
                height: 180
            }).data("kendoWindow");
            skipWindow.content(appBosch.templateSkip(appBosch.qMessages)); //send the row data object to the template and render it
            skipWindow.open().center();  

            $("#yesSButton").on('click',function(){
                getNextQuestion({
                    'skip':true,
                    'id':$(".question").data("idQ")
                });
                skipWindow.close();
            });
            $("#noSButton").on('click',function(){
                skipWindow.close();
            });
        }else{
            getNextQuestion({
                'skip':true,
                'id':$(".question").data("idQ")
            });
        }
    });
    
    $('#question').on('click', 'input[name=answer]', function(e){
        e.stopPropagation();
    });
    
    $('#question').on('click', 'div.answer', function(e){
        e.preventDefault();
        var $answer = $(this).find('input[name=answer]');
        $answer.prop('checked',!$answer.prop('checked'));
    });
    
    $(window).on('beforeunload', function(){
        return appBosch.txtQuitMessage;
    });

    $(window).on('unload', function(){
        $.get( appBosch.urlFinish+'/quit', {}, function(data){
            
        });
    });
}

function getNextQuestion(data){
    var url = appBosch.urlNext;
    data.rndm = Math.random(); //evitar cache
    $.getJSON( url, data, function(data){
        if( data.count <= 1 ){
            $("#skipQuestion").prop('disabled', true);
        }
        $("#nextQuestion").prop('disabled', false);
        if( data.rc === "00" ){
            $(this).prop('disabled', false);
            data.messageVideo = appBosch.messageVideo;
            data.question.mandatory = parseInt(data.question.mandatory);
            $("#question").html(appBosch.template(data)); //mostrar el HTML de la question con sus answers
            data.totalQs = parseInt(data.totalQs);
            data.count = parseInt(data.count);
            $("#progress").html(appBosch.templateProgress({
                'count': ( data.totalQs - data.count ) + 1,
                'totalQs':data.totalQs
            }));
        }else if( data.rc === "01" ){//__('Examen terminado, se terminó el tiempo.');
            $(this).html('Tiempo finalizado');
            quitExamBy('time');
        }else if( data.rc === "02" ){//__('Examen terminado, se terminó el tiempo.');
            $(this).html('Demasiados errores, no se alcanzó la calificación mínima');
            quitExamBy('qualification');
        }else if( data.rc === "04" ){//__('Examen terminado, se terminó el tiempo.');
            $(this).html('Examen terminado, pregunta obligatoria contestada incorrectamente');
            quitExamBy('mandatory');
        }else{ //if "03" Examen finalizado 
            quitExamBy();
        }
    });
}

/**
 * Abandona el examen ya sea dando click en el botón o cerrando el navegador
 * */
function quitExamBy(data){
    turnOffUnload();
    $("#nextQuestion").prop('disabled', true);
    $("#quitExam").prop('disabled', true);
    $("#skipQuestion").prop('disabled', true);
    $(location).attr('href', appBosch.urlFinish+'/'+( data ? ''+data : 'quit'));
}

function turnOffUnload(){
    $(window).off('beforeunload');
    $(window).off('unload');
}

